<template>
  <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible"
             :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item label="社保卡号" prop="medicalCard">
            <el-input v-model="form.medicalCard" placeholder="请输入社保卡号">
              <template #append v-if="!form.id">
                <el-button type="primary" @click="readCard">读卡</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名"/>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="身份证号" prop="icCard">
            <el-input v-model="form.icCard" placeholder="请输入身份证号" @input="inputIcCard"/>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="form.sex">
              <el-radio-button :label="item.value" v-for="(item, index) in gender" border :key="index">{{
                  item.label
                }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="年龄" prop="age">
            <el-input v-model="form.age" placeholder="请输入年龄"/>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="出生日期" prop="birthday">
            <el-date-picker type="date" placeholder="请选择出生日期" v-model="form.birthday"
                            :value-format="dateStr"></el-date-picker>
            <!--            <el-input v-model="form.birthday" placeholder="请输入出生日期"/>-->
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="联系电话" prop="tel">
            <el-input v-model="form.tel" placeholder="请输入联系电话"/>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="地址" prop="address">
            <el-input type="textarea" v-model="form.address" placeholder="请输入地址"/>
          </el-form-item>
        </el-col>

        <!--    <el-col :span="12" class="mb20">-->
        <!--      <el-form-item label="村" prop="village">-->
        <!--        <el-input v-model="form.village" placeholder="请输入村"/>-->
        <!--      </el-form-item>-->
        <!--      </el-col>-->

        <!--        <el-col :span="12" class="mb20">-->
        <!--          <el-form-item label="卡号" prop="localCard">-->
        <!--            <el-input v-model="form.localCard" placeholder="请输入卡号"/>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->

        <el-col :span="12" class="mb20">
          <!--          <el-form-item label="村" prop="village">-->
          <!--            <el-input v-model="form.village" placeholder="请输入村"/>-->
          <!--          </el-form-item>-->

          <el-form-item label="村" prop="village">
            <el-select v-model="form.village" placeholder="请输入村" @change="handleChangeVillage">
              <el-option :label="item.name" :value="item.id" v-for="(item, index) in village"
                         :key="index"/>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="家庭医生" prop="familyDoctor">
            <el-select v-model="form.familyDoctor" placeholder="请输入家庭医生" disabled>
              <el-option :key="item.userId" :label="item.name" :value="item.userId"
                         v-for="item in doctorList"/>
              <!--              <el-option :label="item.label" :value="item.value" v-for="(item, index) in family_doctor" :key="index" />-->
            </el-select>
            <!--						{{ form.doctorName }}-->
          </el-form-item>
        </el-col>


        <el-col :span="12" class="mb20">
          <el-form-item label="管理状态" prop="healthStatus">
            <el-radio-group v-model="form.healthStatus">
              <el-radio-button :label="item.value" v-for="(item, index) in bloodx_health" border :key="index">
                {{ item.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>


        <el-col :span="12" class="mb20">
          <el-form-item label="专病医生" prop="familyDoctor">
            <el-select v-model="form.zbDoctor" placeholder="请输入专病医生">
              <el-option :key="item.userId" :label="item.name" :value="item.userId"
                         v-for="item in ZBDoctorList"/>
            </el-select>
          </el-form-item>
        </el-col>

        <!--    <el-col :span="12" class="mb20">-->
        <!--      <el-form-item label="家庭医生" prop="familyDoctor">-->
        <!--        <el-input v-model="form.familyDoctor" placeholder="请输入家庭医生"/>-->
        <!--      </el-form-item>-->
        <!--      </el-col>-->

        <!--    <el-col :span="12" class="mb20">-->
        <!--      <el-form-item label="体检次数" prop="examNum">-->
        <!--        <el-input v-model="form.examNum" placeholder="请输入体检次数"/>-->
        <!--      </el-form-item>-->
        <!--      </el-col>-->

        <!--    <el-col :span="12" class="mb20">-->
        <!--      <el-form-item label="药品监控字段。0-正常，1-异常" prop="drugStatus">-->
        <!--        <el-input v-model="form.drugStatus" placeholder="请输入药品监控字段。0-正常，1-异常"/>-->
        <!--      </el-form-item>-->
        <!--      </el-col>-->


        <!--        <el-col :span="24">-->
        <!--          <h3 style="margin: 10px 0;font-size: 18px;font-weight: bold;border-bottom: 1px solid #d1d1d1;">常规信息</h3>-->
        <!--        </el-col>-->
        <!--        <el-col :span="12" class="mb20">-->
        <!--          <el-form-item label="身高" prop="height">-->
        <!--            <el-input v-model="form.height" placeholder="请输入身高" @input="inputHeight">-->
        <!--              <template #append>cm</template>-->
        <!--            </el-input>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->

        <!--        <el-col :span="12" class="mb20">-->
        <!--          <el-form-item label="体重" prop="weight">-->
        <!--            <el-input v-model="form.weight" placeholder="请输入体重" @input="inputWeight">-->
        <!--              <template #append>kg</template>-->
        <!--            </el-input>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->

        <!--        <el-col :span="12" class="mb20">-->
        <!--          <el-form-item label="BMI数值" prop="bmi">-->
        <!--            <el-input v-model="form.bmi" placeholder="请输入BMI数值" disabled/>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->

        <!--        <el-col :span="12" class="mb20">-->
        <!--          <el-form-item label="舒张压" prop="bloodPressure">-->
        <!--            <el-input v-model="form.bloodPressure" placeholder="请输入舒张压">-->
        <!--              <template #append>mmHg</template>-->
        <!--            </el-input>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->

        <!--        <el-col :span="12" class="mb20">-->
        <!--          <el-form-item label="收缩压" prop="bloodPressure">-->
        <!--            <el-input v-model="form.bloodPressure" placeholder="请输入收缩压">-->
        <!--              <template #append>mmHg</template>-->
        <!--            </el-input>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->

      </el-row>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="BloodxCustomerSpecialDialog">
import {useDict} from '/@/hooks/dict';
import {useMessage} from "/@/hooks/message";
import {getObj, addObj, putObj} from '/@/api/blood/bloodxCustomerSpecial'
import {getAllZbDoctor, getDoctorList} from "/@/api/information/village";
import {sysVillageList} from "/@/api/blood/bloodxCustomer";
// import { rule } from '/@/utils/validate';
const emit = defineEmits(['refresh']);
// 定义字典
const {bloodx_health, gender} = useDict('bloodx_health', 'gender');
const doctorList = ref<any[]>([]);
const ZBDoctorList = ref<any[]>([]);
// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
// 定义字典
const village = ref([]);
const readCardWs = ref(null);
// 提交表单数据
const form = reactive({
  id: '',
  name: '',
  birthday: '',
  age: 0,
  sex: '',
  icCard: '',
  tel: '',
  address: '',
  village: '',
  localCard: '',
  medicalCard: '',
  healthStatus: '',
  familyDoctor: '',
  examNum: '',
  drugStatus: '',
  height: null,
  weight: null,
  bloodPressure: '',
  bmi: '',
  doctorName: '',
  zbDoctor: '',

});

// 定义校验规则
const dataRules = ref({
  name: [{required: true, message: '请输入姓名', trigger: 'blur'}],
  healthStatus: [{required: true, message: '请选择管理状态', trigger: 'blur'}],
  sex: [{required: true, message: '请选择性别', trigger: 'blur'}],
})

const handleChangeVillage = (id: Object) => {
  form.familyDoctor = village.value.find((item) => item.id === id).doctorId;
  form.doctorName = village.value.find((item) => item.id === id).doctorName;
};

const inputIcCard = (val: string) => {
  if (val.length === 18) {
    form.birthday = val.substring(6, 10) + '-' + val.substring(10, 12) + '-' + val.substring(12, 14);
    form.sex = parseInt(val.substring(16, 17)) % 2 === 0 ? '2' : '1';
    form.age = new Date().getFullYear() - parseInt(val.substring(6, 10))
  }
};

const readCard = async () => {
  loading.value = true;
  try {
    sendReadCard("ws://127.0.0.1:2018", (message) => {
      if (JSON.parse(message).Data.IsSuccess === false) {
        useMessage().error(JSON.parse(message).Data.msg)
        return;
      }
      useMessage().success('读卡成功');
      let list = JSON.parse(message).Data.kh.split("|")
      // console.log(list);
      form.name = list[4]
      form.medicalCard = list[2]
      form.icCard = list[1]
      form.localCard = list[2]
      inputIcCard(form.icCard)
    });
    // const readRes = await sendReadCard();
    // if (readRes.code == 0) {
    // 	useMessage().success(readRes.msg);
    // 	form.name = '张三';
    // 	form.birthday = '1990-01-01';
    // 	form.age = 30;
    // 	form.medicalCard = readRes.data;
    // }
  } finally {
    loading.value = false;
  }
};

const sendReadCard = (WSURL: any, callback: any) => {
  if (readCardWs.value !== null) {
    if (
        readCardWs.value.readyState === 0 ||
        readCardWs.value.readyState === 1
    ) {
      return;
    } else {
      readCardWs.value.close();
    }
  }
  readCardWs.value = new WebSocket(WSURL);
  readCardWs.value.addEventListener("open", () => {
    readCardWs.value.send("读卡");
  });

  readCardWs.value.addEventListener("close", () => {
  });

  readCardWs.value.addEventListener("error", () => {
    readCardWs.value.close();
    useMessage().error('读卡失败');
  });

  readCardWs.value.addEventListener("message", (message) => {
    if (message.data !== "Open!") {
      readCardWs.value.close();
      callback(message.data);
    }

  });
}

const getdoctorList = () => {
  getDoctorList().then((res) => {
    doctorList.value = res.data;
  });

  getAllZbDoctor().then((res) => {
    ZBDoctorList.value = res.data;
  });


};

// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true
  form.id = ''
  sysVillageList().then((res) => {
    village.value = res.data;
  });
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });

  // 获取bloodxCustomerSpecial信息
  if (id) {
    form.id = id
    getbloodxCustomerSpecialData(id)
  }

  getdoctorList();
};

// const inputHeight = () => {
//   if (form.weight) {
//     form.bmi = (form.weight / ((form.height / 100) * (form.height / 100))).toFixed(2);
//   }
// };
//
// const inputWeight = () => {
//   if (form.height) {
//     form.bmi = (form.weight / ((form.height / 100) * (form.height / 100))).toFixed(2);
//   }
// };

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {
  });
  if (!valid) return false;

  try {
    loading.value = true;
    if (form.birthday && form.birthday.indexOf(':') === -1) {
      form.birthday += ' 00:00:00';
    }
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};


// 初始化表单数据
const getbloodxCustomerSpecialData = (id: string) => {
  // 获取数据
  loading.value = true
  getObj(id).then((res: any) => {
    Object.assign(form, res.data)
  }).finally(() => {
    loading.value = false
  })
};

// 暴露变量
defineExpose({
  openDialog
});
</script>

<style scoped>
.radius {
  border: 1px solid var(--el-border-color);
  margin-top: 20px;
  border-radius: 4px;
}

.el-input-group__append button.el-button {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary);
  color: var(--el-color-white);
}
</style>
